<template>
  <div id="admin">
    <div class="titleBar">
      <div>角色管理</div>
      <div>
        <el-button
          type="primary"
          @click="(dialogVisible = true), (isAdd = true)"
          >新增角色</el-button
        >
      </div>
    </div>
    <div class="tabBar">
      <div class="role-man" v-for="(item, index) in list" :key="index">
        <div class="r-picture">
          <img src="./ar86e-xh183.jpg" alt="" />
        </div>
        <div class="r-text">
          <div>{{ item.rolename }}</div>
          <div>{{ item.remark }}</div>
        </div>
        <div class="r-button">
          <span @click="updateRole(item)"
            ><i class="el-icon-edit-outline"></i></span
          ><span @click="settingMenu(item)"
            ><i class="el-icon-s-tools"></i></span
          ><span class="delete" @click="deletedRole(item)"
            ><i class="el-icon-delete"></i
          ></span>
        </div>
      </div>
    </div>

    <!-- 修改或新增菜单 -->
    <el-dialog
      :title="isAdd ? '新增角色' : '修改'"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
      :close-on-click-modal="false"
    >
      <el-form :model="form" ref="form" :rules="rules" label-width="80px">
        <el-form-item label="角色名称" prop="rolename">
          <el-input v-model="form.rolename" clearable></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="form.remark"></el-input>
        </el-form-item>
        <el-form-item label="Tag颜色">
          <el-color-picker v-model="form.color" show-alpha></el-color-picker>
        </el-form-item>
        <el-form-item label="Tag文字颜色">
          <el-color-picker
            v-model="form.textColor"
            show-alpha
          ></el-color-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitBtn('form', form)"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 为角色分配菜单 -->
    <div class="dialog_menu_admin">
      <el-dialog
        title="权限设置"
        :visible.sync="dialogVisibleTwo"
        width="30%"
        :before-close="handleCloseTwo"
        :close-on-click-modal="false"
      >
        <div style="margin-bottom: 5px">选中内容：</div>
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="菜单权限" name="menu"
            ><div>
              <div style="display: flex; margin-bottom: 15px">
                <el-button
                  size="mini"
                  type="primary"
                  :icon="
                    isExpandAll ? 'el-icon-arrow-down' : 'el-icon-arrow-right'
                  "
                  @click="(isExpandAll = !isExpandAll), expandTree++"
                >
                  {{ isExpandAll ? "全部收起" : "全部展开" }}
                </el-button>
                <el-button
                  size="mini"
                  type="primary"
                  :icon="isSelectAll ? 'el-icon-close' : 'el-icon-check'"
                  @click="menuSelectAll()"
                >
                  {{ isSelectAll ? "全部取消" : "全部选择" }}
                </el-button>
              </div>
              <div :key="expandTree">
                <el-tree
                  ref="treeRef"
                  :props="props"
                  :data="data"
                  show-checkbox
                  @check-change="handleCheckChange"
                  @check="handleClickChange"
                  :check-strictly="true"
                  node-key="menu_id"
                  :default-checked-keys="roleMenuData"
                  :highlight-current="true"
                  :check-on-click-node="true"
                  :default-expand-all="isExpandAll"
                >
                </el-tree>
              </div></div
          ></el-tab-pane>
          <el-tab-pane label="新闻审核" name="news">该功能暂未开放</el-tab-pane>
        </el-tabs>

        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisibleTwo = false">取 消</el-button>
          <el-button type="primary" @click="dialogVisibleTwo = false"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  addrole,
  updateRole,
  deleteRoleById,
  getRoleList,
  roleAddMenu,
  roleDeleteMenu,
  getRoleMenuIdList,
  getAllmenu,
} from "@/api/role";
import { getUseMenuList, getAllmenu1 } from "@/api/menuManagement";
import { Row } from "element-ui";

export default {
  data() {
    var checkwrite = (rules, value, text) => {
      const regRole =
        /^(?:[\u3400-\u4DB5\u4E00-\u9FEA\uFA0E\uFA0F\uFA11\uFA13\uFA14\uFA1F\uFA21\uFA23\uFA24\uFA27-\uFA29]|[\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0])+$/;
      if (regRole.test(value)) {
        return text();
      }
      text(new Error("请输入正确的角色"));
    };

    return {
      dialogVisible: false,
      dialogVisibleTwo: false,
      isAdd: true,
      textColor: "rgba(255,255,255,1)",
      form: {
        rolename: "",
        remark: "",
        color: "rgba(64,158,255,1)",
        textColor: "rgb(255,255,255,1)",
      },
      list: [],
      rules: {
        rolename: [
          { required: true, min: 1, validator: checkwrite, trigger: "blur" },
        ],
      },

      //树形菜单
      props: {
        label: "label",
        children: "children",
      },
      count: 1,
      data: [],
      role_id: "",

      //查看角色菜单
      roleMenuData: [],

      //是否默认展开所有节点
      isExpandAll: false,
      isSelectAll: false,
      expandTree: 0, //刷新
      //tabs标签页
      activeName: "menu",
    };
  },

  created() {
    this.init();
  },

  methods: {
    init() {
      this.getRoleList();
    },

    getRoleList() {
      getRoleList().then((res) => {
        this.list = res.data;
      });
    },

    //提交按钮
    submitBtn(form, data) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          if (this.isAdd) {
            addrole(data).then((res) => {
              if (res.code == 0) {
                this.dialogVisible = false;
                this.$message({
                  type: "success",
                  message: "你新增了一个角色",
                });
                this.init();
              }
            });
          } else {
            updateRole(data).then((res) => {
              if (res.code == 0) {
                this.dialogVisible = false;
                this.$message({
                  type: "success",
                  message: "修改角色成功",
                });
                this.init();
              }
            });
          }
        } else {
          return false;
        }
      });
    },

    //设置菜单
    settingMenu(role_id) {
      this.role_id = role_id.id;
      this.dialogVisibleTwo = true;
      getAllmenu1().then((res) => {
        let data = [];
        let menuData = res.data;
        menuData.forEach((element) => {
          let menu = {
            menu_id: element.menu_id,
            label: element.title,
          };
          if (element.children) {
            menu.children = [];
            let child = element.children;
            child.forEach((item) => {
              let children = {
                menu_id: item.menu_id,
                label: item.title,
              };
              if (item.children) {
                children.children = [];
                let grand = item.children;
                grand.forEach((menu_min) => {
                  let grandson = {
                    menu_id: menu_min.menu_id,
                    label: menu_min.title,
                  };
                  children.children.push(grandson);
                });
              }
              menu.children.push(children);
            });
          }
          data.push(menu);
        });
        this.data = data;
      });

      //查看角色菜单
      let id = {
        role_id: this.role_id,
      };
      getRoleMenuIdList(id).then((res) => {
        let roleMenu_Data = res.data;
        this.roleMenuData = roleMenu_Data;
      });
    },

    //删除角色
    deletedRole(item) {
      let id = item.id;
      let ids = {
        id,
      };
      const h = this.$createElement;
      this.$msgbox({
        title: "提示",
        message: h("p", null, [
          h("span", null, "此操作将永久删除 "),
          h("i", { style: "color: teal" }, item.rolename),
          h("span", null, " 这个角色"),
          h("span", "（与该角色关联的菜单，将一同删除）"),
          h("span", null, "，是否继续？"),
        ]),
        showCancelButton: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteRoleById(ids).then((res) => {
            if (res.code == 0) {
              this.$message({
                type: "success",
                message: res.data,
              });
              this.init();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    //修改角色信息
    updateRole(row) {
      this.form = Object.assign({}, row);
      this.isAdd = false;
      this.dialogVisible = true;
    },

    //关闭新增/修改弹窗
    handleClose(done) {
      let a = this.form.rolename;
      if (a == "") {
        this.dialogVisible = false;
      } else {
        this.$confirm("你还未提交信息，确认关闭？")
          .then((_) => {
            done();
          })
          .catch((_) => {});
      }
    },

    //关闭分配菜单弹窗
    handleCloseTwo(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },

    //树形菜单点击时回调
    handleClickChange(data, state) {
      let a = this.roleMenuData.includes(data.menu_id);
      if (a) {
        let delparent = {
          role_id: this.role_id,
          menu_id: data.menu_id,
        };
        roleDeleteMenu(delparent).then((res) => {
          if (res.code == 0) {
            this.$message({
              message: "你删除了一个权限",
              type: "warning",
            });
            this.roleMenuData = state.checkedKeys;
          } else {
            this.$message({
              message: "出现了未知的错误",
              type: "error",
            });
          }
        });
      } else {
        let addChild = {
          role_id: this.role_id,
          menu_id: data.menu_id,
        };
        roleAddMenu(addChild).then((res) => {
          if (res.code == 0) {
            this.$message({
              message: "你添加了一个权限",
              type: "success",
            });
            this.roleMenuData = state.checkedKeys;
          } else {
            this.$message({
              message: "出现了未知的错误",
              type: "error",
            });
          }
        });
      }
    },

    //树形菜单发生变化时回调
    handleCheckChange(data, checked, indeterminate) {},

    //tabs标签页
    handleClick(tab, event) {},

    //一键选择全部菜单
    menuSelectAll() {
      this.isSelectAll = !this.isSelectAll;
      if (this.isSelectAll) {
        this.$refs.treeRef.setCheckedNodes(this.data);
      } else {
        this.$refs.treeRef.setCheckedNodes([]);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
#admin {
  height: calc(100vh - 84px);
  width: 100%;
  background-color: #ffffff;
  padding: 0 20px 0 0;
  overflow: auto;
  position: relative;

  .titleBar {
    border-bottom: 1px solid #0000002e;
    height: 70px;
    line-height: 70px;
    display: flex;
    justify-content: space-between;
    // margin-bottom: 20px;
    margin-left: 20px;
  }

  .tabBar {
    height: calc(100vh - 154px);
    overflow: auto;
    // background-color: aqua;
    display: flex;
    flex-wrap: wrap;
    padding-top: 20px;
    align-content: flex-start;

    .role-man {
      // background-color: rgb(229, 151, 151);
      height: 306px;
      width: 256px;
      border-radius: 13px;
      margin-bottom: 20px;
      margin-left: 20px;
      overflow: hidden;
      z-index: 100;

      .r-picture {
        width: 256px;
        aspect-ratio: 16/9;

        img {
          width: 256px;
          aspect-ratio: 16/9;
          display: block;
        }
      }

      .r-text {
        width: 256px;
        height: calc(306px - 179px);
        box-sizing: border-box;
        border-left: 1px solid #d3d4d6;
        border-right: 1px solid #d3d4d6;
        padding: 10px;

        div {
          width: 100%;
        }

        :nth-child(1) {
          color: #409eff;
          font-size: 23px;
          height: 48px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        :nth-child(2) {
          height: 59px;
          font-size: 15px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }

      .r-text:hover {
        border-left: 0px;
        border-right: 0px;
      }

      .r-button {
        width: 256px;
        height: 35px;
        // #d3d4d6
        display: flex;
        background-color: rgb(229, 151, 151);

        span {
          background: #d3d4d6;
          width: calc(256px / 3);
          height: 35px;
          display: block;
          line-height: 35px;
          text-align: center;

          ::v-deep i {
            color: #6a6a6a;
          }
        }

        span:hover {
          background-color: #409eff;

          ::v-deep i {
            color: #ffffff;
          }
        }

        .delete:hover {
          background: #f56c6c;
        }
      }
    }

    .role-man:hover {
      box-shadow: 0 10px 34px rgb(31 45 61 / 40%);
      transform: scale(1.1);
      transition-duration: 0.5s;
    }
  }

  .dialog_menu_admin {
    ::v-deep .el-dialog {
      margin-top: 8vh !important;
      width: 55% !important;

      .el-dialog__body {
        padding: 10px 20px;

        .el-tree {
          height: 400px;
          overflow: auto;
        }
      }
    }
  }
}
</style>